<?php
// 作者复制PC端链接在浏览器上发布文章


require '../framework/bootstrap.inc.php';
require IA_ROOT . '/web/common/bootstrap.sys.inc.php';

load()->web('common');
load()->web('template');
global $_W,$_GPC;

load()->func('tpl');
if(empty($_GPC['key'])){
    echo "你的访问无效";
    exit();
}


$key=$_GPC['key'];
$sql="select * from ".tablename('dg_article')." where `key`='$key'";
$ainfo=pdo_fetch($sql);

$uniacid=$ainfo['uniacid'];

//入口链接
$modulename = "dg_articlemanage";
$module = $_W['current_module'] = module_fetch($modulename);
$entries = module_entries($modulename);
$rukouUrl=$_W['siteroot']."app/index.php?i=".$uniacid."&c=entry&eid=".$entries['cover'][0]['eid'];

$category = pdo_fetchall("SELECT * FROM ".tablename('dg_article_category')." WHERE uniacid =:uniacid ORDER BY parentid ASC,displayorder,id ", array(":uniacid"=>$uniacid));
$parent = array();
$children = array();
if (!empty($category)) {
    
    foreach ($category as $cid => $cate) {
        if (!empty($cate['parentid'])) {
            $children[$cate['parentid']][] = $cate;
        } else {
            $parent[$cate['id']] = $cate;
        }
    }
}

$id = intval($ainfo['id']);    
load()->func('file');
$pcate = $_GPC['pcate'];
$ccate = $_GPC['ccate'];
if ($id>0) {
    $item = pdo_fetch("SELECT * FROM ".tablename('dg_article')." WHERE id = :id" , array(':id' => $id));

    if (empty($item)) {
        message('抱歉，文章不存在或是已经删除！', '', 'error');
    }
    $pcate = $item['pcate'];
    $ccate = $item['ccate'];
    $akeywords = pdo_fetchcolumn('SELECT content FROM ' . tablename('rule_keyword') . ' WHERE id = :id AND uniacid = :uniacid ', array(':id' => $item['kid'], ':uniacid' => $_W['uniacid']));
    $item['type'] = explode(',', $item['type']);
    $item['credit'] = iunserializer($item['credit']) ? iunserializer($item['credit']) : array();
    if(!empty($item['credit']['limit'])) {
        $credit_num = pdo_fetchcolumn('SELECT SUM(credit_value) FROM ' . tablename('mc_handsel') . ' WHERE uniacid = :uniacid AND module = :module AND sign = :sign', array(':uniacid' => $_W['uniacid'], ':module' => 'dg_article', ':sign' => md5(iserializer(array('id' => $id)))));
        if(is_null($credit_num)) $credit_num = 0;
        $credit_yu = (($item['credit']['limit'] - $credit_num) < 0) ? 0 : $item['credit']['limit'] - $credit_num;
    }
    $ausql="select * from ".tablename('dg_article_author')." where id=:aid and uniacid=:uniacid";
    $parms=array(":aid"=>$item['author_id'],":uniacid"=>$uniacid);
    $saler=pdo_fetch($ausql,$parms);
} else{
    $item['bg_music_switch'] ='1';
    $item['credit'] = array();
}


// 上传url
$uploadUrl=$_W['siteroot'].'web/setarticle.php?key='.$_GPC['key'];
// 远程处理    (远程变量  $_W['setting']['remote'][11])
$yuancheng=$_W['setting']['remote'][$uniacid];  // 位置禁止下移
if($yuancheng['type']){
    $_W['setting']['remote']['type']=$yuancheng['type'];

    $domain=''; //远程域名前缀
    switch ($yuancheng['type']) {
        case '1':
            $_W['setting']['remote']['ftp']=$yuancheng['ftp'];
            $domain=$yuancheng['ftp']['url']."/";
            break;
        case '2':
            $_W['setting']['remote']['oss']=$yuancheng['oss'];
            $domain=$yuancheng['oss']['url']."/";
            break;
        case '3':
            $_W['setting']['remote']['qiniu']=$yuancheng['qiniu'];
            $domain=$yuancheng['qiniu']['url']."/";
            break;
        case '4':
            $_W['setting']['remote']['cos']=$yuancheng['cos'];
            $domain=$yuancheng['cos']['url']."/";
            break;
    }

    $yuancheng['url']=$domain;
}

//上传图片类型文章的  图片内容 （进行缩略）
if($_GPC['tp'] == 'upImg'){
    if(IS_AJAX){  
        $resArr=upImages($uniacid,"image_data",$yuancheng,$_W['attachurl_local'],$_GPC['ysb']);
    
        echo json_encode($resArr);
    }  
    return 1; //这个返回值必须要  
}

//上传音视频类型文章的  音视频文件  
if($_GPC['tp'] == 'upAudio' || $_GPC['tp'] == 'upVedio'){
    switch ($_GPC['tp']) {
        case 'upAudio':
            $html_thumb_name="bg_music";
            $avtp="audio";
            break;
        case 'upVedio':
            $html_thumb_name="vedio_url";
            $avtp="vedio";
            break;  
    }

    if(IS_AJAX){  
        $resArr=upThumbAV($uniacid,$html_thumb_name,$yuancheng,$_W['attachurl_local'],$avtp);
        
        echo json_encode($resArr);
    }  
    return 1; //这个返回值必须要  
}

//图文类型时  富文本编辑器的图片上传 （进行缩略）
if($_GPC['tp'] == 'mce'){

    if(IS_AJAX){  
        $resArr=upImages($uniacid,"file",$yuancheng,$_W['attachurl_local']);
        $res['location']=$resArr[0];
        echo json_encode($res);
    } 
    return true;
}

//删除 已上传文件
if($_GPC['tp'] == "delupFile"){
    if(IS_AJAX){        
        $result=deleteupFile($_POST['urlArr']);
        // 此处不做成功失败判断 只返回成功
        header('content-type:application/json;charset=utf8');
        $res['message']="success";
        echo json_encode($res);  
    }
}

if ($_GPC['submit']=="提交") {
    
    // 处理封面图 (不进行缩略)
    $thumbPath=upThumbAV($uniacid,"thumb",$yuancheng,$_W['attachurl_local'],'thumb');

    $data = array(
        'uniacid' => $uniacid,
        'pcate' => intval($_GPC['catagroy']['parentid']),
        'ccate' => intval($_GPC['catagroy']['childid']),
        'title' => $_GPC['title'],
        'thumb' => $thumbPath[0],
        'types' => $_GPC['types'],
        'pay_money'=>$_GPC['pay_money'],
        'createtime' => time(),
        //'wailian'=>$_GPC['wailian']
    );

    if($_GPC['types']==1){
        $data['description'] = htmlspecialchars_decode($_GPC['description']);
        $data['content'] = htmlspecialchars_decode($_GPC['content']);
    }

    if($_GPC['types']==2){
        $data['images'] = $_GPC['images'];
        $data['img_free'] = $_GPC['img_free'];
    }

    $DelFIleArr=[]; // 音视频用到
    if($_GPC['types']==3){
        if(trim($_GPC['bg_music_lianjie'])){
            if($_GPC['bg_music']){
                array_push($DelFIleArr, $_GPC['bg_music']);
                deleteupFile($DelFIleArr);
                unset($DelFIleArr);
            }
            $data['bg_music'] = trim($_GPC['bg_music_lianjie']);
        }else{
            $data['bg_music'] = $_GPC['bg_music'];
        }
        $data['aud_free'] = $_GPC['aud_free'];
    }  

    if($_GPC['types']==4){  
        if(trim($_GPC['vedio_url_lianjie'])){
            if($_GPC['vedio_url']){
                array_push($DelFIleArr, $_GPC['vedio_url']);
                deleteupFile($DelFIleArr);
                unset($DelFIleArr);
            }
            $data['vedio_url'] = trim($_GPC['vedio_url_lianjie']);
        }else{
            $data['vedio_url'] = $_GPC['vedio_url'];
        }

        $data['ved_free'] = $_GPC['ved_free'];
    }


    if(!empty($_GPC['akeyword'])) {
        $rule['uniacid'] = $_W['uniacid'];
        $rule['name'] = '文章：' . $_GPC['title'] . ' 触发规则';
        $rule['module'] = 'news';
        $rule['status'] = 1;

        $keyword = array('uniacid' => $_W['uniacid']);
        $keyword['module'] = 'news';
        $keyword['content'] = $_GPC['akeyword'];
        $keyword['status'] = 1;
        $keyword['type'] = 1;
        $keyword['displayorder'] = 1;
        $reply['title'] = $_GPC['title'];
        $reply['description'] = $_GPC['description'];
        $reply['thumb'] = $data['thumb'];
        $reply['url'] = murl('entry/module/detail', array('m'=>'dg_articlemanage','id' => $id));

    }

    if(!empty($_GPC['akeyword'])) {
        pdo_insert('rule', $rule);
        $rid = pdo_insertid();

        $keyword['rid'] = $rid;
        pdo_insert('rule_keyword', $keyword);
        $kid = pdo_insertid();

        $reply['rid'] = $rid;
        pdo_insert('news_reply', $reply);
        $data['rid'] = $rid;
        $data['kid'] = $kid;
    }

    pdo_update('dg_article', $data,array('id'=>$id));
  
    pdo_update('news_reply', array('url' => murl('entry/module/detail', array('m'=>'dg_articlemanage', 'id' => $id))), array('rid' => $rid));


    header("Location:". $_W['siteroot']."web/setarticle.php?key=".$key."&d=1");
}

template('setarticle');
/*include IA_ROOT.'/web/setarticle.html';*/

// 上图片类型文章, 内容: 图片的上传处理  |   富文本图片上传处理
/*
*  @param $uniacid  微擎标识id
*  @param $html_thumb_name  html页面中 input的name
*  @param $setting   远程
*  @param $attachurl_local   $_W['attachurl_local']
*  @param $compress  图片压缩比
*/
function upImages($uniacid,$html_thumb_name,$setting,$attachurl_local,$compress){
    // 注： $html_thumb_name 富文本上传图片 值固定 file

    if(empty($uniacid) || empty($html_thumb_name) || empty($attachurl_local)) return "";
    
    $year=date('Y');
    $m=date('m');

    if($html_thumb_name == 'file'){  
        $str="imagesmce/$uniacid/$year"; 
    }else{
        $str="images/$uniacid/$year"; 
    }

    if(file_exists(IA_ROOT . "/attachment/".$str) == false){
        makeDir(IA_ROOT . "/attachment/".$str,0777);
    }
    if(file_exists(IA_ROOT . "/attachment/".$str."/$m") == false){
        makeDir(IA_ROOT . "/attachment/".$str."/$m",0777);
    }

    $res=[];
    
    if($html_thumb_name == 'file'){   //富文本图片上传
        $filename= date('YmdHis').mt_rand(10000,99999);
        $tmp = $_FILES[$html_thumb_name]['tmp_name'];
        if(!empty($tmp)){   
            $pathname=  $str."/$m/mce"  . $filename. '.png';
            move_uploaded_file($tmp, IA_ROOT . "/attachment/".$str."/$m/mce" . $filename. '.png');   

            if(!empty($setting['type'])){
                $remotestatus = file_remote_upload($pathname); //上传图片到远程
                if (!is_error($remotestatus)) {
                    //远程上传成功
                    $remoteurl = $setting['url'].$pathname;  // 远程图片的访问URL         
                }
                array_push($res,  $remoteurl);
            }else{
                array_push($res, $attachurl_local.$pathname);
            }
        }else{
            array_push($res,'');
        }
    }else{

       foreach ($_FILES[$html_thumb_name]['tmp_name'] as $key => $tmp) {

            $filename= date('YmdHis').mt_rand(10000,99999);
            if(!empty($tmp)){
                $pathname=  $str."/$m/"  . $filename. '.png';
                
                if($compress){
                    move_uploaded_file($tmp, IA_ROOT . "/attachment/".$str."/$m/LZ" . $filename. '.png'); 
                    
                    $result=imagepress(IA_ROOT . "/attachment/".$str."/$m/LZ" . $filename. '.png',$filename. '.png',$compress);

                    if($result){
                        $pathname=$pathname;
                        @unlink(IA_ROOT . "/attachment/".$str."/$m/LZ" . $filename. '.png');
                    }else{
                        $pathname=$str."/$m/LZ" . $filename. '.png';
                    }     

                }else{
                    move_uploaded_file($tmp, IA_ROOT . "/attachment/".$str."/$m/" . $filename. '.png');
                    $pathname=$pathname;                     
                }
                if(!empty($setting['type'])){
                    $remotestatus = file_remote_upload($pathname); //上传图片到远程

                    if (!is_error($remotestatus)) {
                        //远程上传成功

                        $remoteurl = $setting['url'].$pathname;  // 远程图片的访问URL         
                    }
                    array_push($res,  $remoteurl);
                }else{
                    array_push($res, $attachurl_local.$pathname);
                }
            }else{
                array_push($res,'');
            }
        }     
    }
    
    return $res;
}

// 上传音视频 封面图 
/*
*  @param $uniacid  微擎标识id
*  @param $html_thumb_name  html页面中 input的name
*  @param $setting   $_W['setting']['remote']
*  @param $attachurl_local   $_W['attachurl_local']
*  @param $avtp 封面图 音频 视频分类 （ thumb ｜ audio  ｜ vedio）
*
*/
function upThumbAV($uniacid,$html_thumb_name,$setting,$attachurl_local,$avtp){
    
    if(empty($uniacid) || empty($html_thumb_name) || empty($attachurl_local) || empty($avtp)) return '';

    $filename= date('YmdHis').mt_rand(1000,9999);
    $year=date('Y');
    $m=date('m');

    switch ($avtp) {
        case 'thumb':
            $dirStr="images";
            //$dirStr="imagesdoudou";//ceshi
            $hou=".png";
            break;
        case 'audio':
            $dirStr="audios";
            //$dirStr="audiosdoudou";//ceshi
            $hou=".mp3";
            break;
        case 'vedio':
            $dirStr="vedios";
            //$dirStr="vediosdoudou";//ceshi 
            $hou=".mp4";
            break;
    }

    $str=$dirStr."/$uniacid/$year";

    if(file_exists(IA_ROOT . "/attachment/".$str) == false){
        makeDir(IA_ROOT . "/attachment/".$str,0777);
    }
    if(file_exists(IA_ROOT . "/attachment/".$str."/$m") == false){
        makeDir(IA_ROOT . "/attachment/".$str."/$m",0777);
    }

    $tmp=$_FILES[$html_thumb_name]['tmp_name']; //临时文件名

    $res=[];
    if(!empty($tmp)){
        move_uploaded_file($tmp, IA_ROOT . "/attachment/".$str."/$m/" . $filename. $hou);  
        $pathname=  $str."/$m/"  . $filename. $hou;
        if(!empty($setting['type'])){
            $remotestatus = file_remote_upload($pathname); //上传图片到远程
            if (!is_error($remotestatus)) {
                //远程上传成功
                $remoteurl = $setting['url'].$pathname;  // 远程图片的访问URL         
            }
            array_push($res,  $remoteurl);
        }else{
            array_push($res, $attachurl_local.$pathname);
        }
    }else{
        array_push($res,'');
    }

    return $res;

}

//缩放图片
/*
* @param $filepath 文件路径
* @param $newName 新文件的名字（只是文件名，无目录路径）
* @param $percent  缩放比
* return 返回缩放后的图片的路径,返回的图片仍以原图名称命名，原图删除
*
*   注：本文件中图片存储为 png格式，故本函数中图片处理函数使用png格式函数
*/
function imagepress($filepath,$newName,$percent){
    // 图片类型
    //header('Content-Type: image/png');
    // 获得新的图片大小
    list($width, $height,$type) = getimagesize($filepath);

    $img_type=image_type_to_extension($type,false);//图片类型
    $new_width = $width * $percent;
    $new_height = $height * $percent;

    // 重新取样
    $image_p = imagecreatetruecolor(ceil($new_width), ceil($new_height));
    $func_1 = "imagecreatefrom".$img_type;
    $image = $func_1($filepath);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    // 输出
    $func_2="image".$img_type;
    return $func_2($image_p, dirname($filepath)."/".$newName);
}

// 删除文件
/*
* @param $pathArr 文件的有效链接  （函数内分析物理路径，只删除本地服务器文件，远程不删除）
*/
function deleteupFile($pathArr){

    if(empty($pathArr) || !is_array($pathArr)) return '';

    foreach ($pathArr as $key => $value) {
        $filePath=IA_ROOT.substr($value,strpos($value, "attachment")-1);
        if(file_exists($filePath)){
            @unlink($filePath);
        }
    }

    return '';
}

// 创建文件夹 (上朔函数)
function  makeDir($dir, $mode = 0777) {
    if (!$dir) return false;

    if(!file_exists($dir)) {
        mkdir($dir,$mode,true);
        return chmod($dir,$mode);
    } else {
        return true;
    }
    
}